package com.example.musicplayer.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class MusicVisualizerView extends View {
    private static final int DENSITY = 3;
    private byte[] mWaveFormData;
    private Paint mPaint;
    private Rect mRect;

    public MusicVisualizerView(Context context) {
        this(context, null);
    }

    public MusicVisualizerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MusicVisualizerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setup();
    }

    private void setup() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.GREEN);
        mRect = new Rect();
        mWaveFormData = null;
    }

    public void update(byte[] data) {
        if (data != null) {
            mWaveFormData = data;
            invalidate();
        }
    }

    public void setColor(int color) {
        mPaint.setColor(color);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mWaveFormData != null) {
            int waveWidth = getWidth() / (mWaveFormData.length / DENSITY);
            mRect.set(0, 0, getWidth(), getHeight());
            for (int i = 0; i < mWaveFormData.length - 1; i += DENSITY) {
                float left = (float) getWidth() * i / (mWaveFormData.length - 1);
                float top = (float) (Math.abs(mWaveFormData[i + 1]) * mRect.height()) / 128;
                float right = left + waveWidth;
                float bottom = mRect.height();
                canvas.drawRect(left, top, right, bottom, mPaint);
            }
        }
    }
}